const { User } = require("../model"); // requie加载文件时 就会执行加载的js
const { createToken } = require("../util/jwt");
// 用户路由模块逻辑
const register = async (req, res) => {
  const userModel = new User(req.body);
  const dbJSON = await userModel.save();
  const user = dbJSON.toJSON();
  delete user.password;
  res.status(201).send({ user });
};

const login = async (req, res) => {
  let dbBack = await User.findOne(req.body);
  if (dbBack) {
    dbBack = dbBack.toJSON() // ?? 暂时没想明白数据库返回的对象还要在 toJSON 一次 ?
    const token = await createToken(dbBack)
    dbBack.token = token
    res.status(200).json(dbBack)
  }else{
    res.status(402).json({error:'邮箱或者密码错误!'})
  }
};

const getList = async (req,res) => { 
   console.log(req.user,'----- 可以获取到鉴权时中间件存储的用户数据 ------');
   res.status(200).send('====== get List =====')
}

module.exports = {
  register,
  login,
  getList
};
